import 'package:flutter/material.dart';

import '../../repository/sjx_api.dart';
import '../../utils/sp_utils.dart';

class PersonEditPage extends StatefulWidget {
  final String initialName;
  final Function(String) onSave;

  const PersonEditPage({
    super.key,
    required this.initialName,
    required this.onSave,
  });

  @override
  State<PersonEditPage> createState() => _PersonEditPageState();
}

class _PersonEditPageState extends State<PersonEditPage> {
  late TextEditingController _textController;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController(text: widget.initialName);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    _textController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _cancel() {
    Navigator.of(context).pop();
  }

  void _save() async {
    final String newName = _textController.text.trim();

    if (newName.isEmpty) {
      _showMessage('昵称不能为空');
      return;
    }

    if (newName == widget.initialName) {
      Navigator.of(context).pop();
      return;
    }

    // 显示加载提示
    _showLoadingDialog('正在保存');

    try {
      await SJXApi.instance().updateUserInfo({"nickName": newName});
      final user = await SpUtils.getUserData();
      if (user != null) {
        final updatedUser = user.copyWith(userName: newName);
        SpUtils.saveUserData(updatedUser);
      }

      // 关闭加载提示
      if (mounted) Navigator.of(context).pop();

      // 回调保存结果
      widget.onSave(newName);

      // 返回上一页
      if (mounted) Navigator.of(context).pop();
    } catch (e) {
      if (mounted) Navigator.of(context).pop();
      _showMessage('保存失败: $e');
    }
  }

  Future<void> _updateUserName(String newName) async {
    // 模拟API调用延迟
    await Future.delayed(const Duration(seconds: 1));

    // 这里应该调用实际的更新用户信息API
    // 例如：
    // await apiService.updateUserInfo({'nickName': newName});

    // 更新本地用户信息
    // UserManager.updateUserName(newName);
  }

  void _showLoadingDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const CircularProgressIndicator(),
              const SizedBox(height: 16),
              Text(message),
            ],
          ),
        );
      },
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设置昵称'),
        actions: [
          TextButton(
            onPressed: _save,
            child: const Text(
              '完成',
              style: TextStyle(
                color: Color(0xFF1890FF),
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: TextField(
          controller: _textController,
          focusNode: _focusNode,
          decoration: const InputDecoration(
            hintText: '请输入昵称',
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(horizontal: 0),
          ),
          style: const TextStyle(
            fontSize: 16,
            color: Color(0xFF262626),
          ),
          maxLength: 20,
          textInputAction: TextInputAction.done,
          onSubmitted: (_) => _save(),
        ),
      ),
    );
  }
}